﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

using CE.User;
using CE.Global;
using CE.Provider;
using CE.Image;

public partial class Provider_TravelInsurance_ProviderTIPolicyWriting : System.Web.UI.Page
{
    string PageName = "CXTI";
    string SubPageName = "CXTIPL";
    public static Int64 _providerdocumentid = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null || Session[CE.Global.General.ProviderCompanyId] == null)
        {
            Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        }
        CheckMainPageAccess();
        CheckSubPageAccess();

        if (!IsPostBack)
        {
            //string _authcode = CE.Security.MySecurity.Decrypt("GjT5ZicIKgvM/DJvpBYTWA==", true);
            ClearProcess();
            if (Request.Params["PWID"] != null)
            {
                Int32 _policydocid;
                if (Int32.TryParse(Request.Params["PWID"].ToString(), out _policydocid))
                {
                    ShowPolicy(_policydocid);
                }
            }
        }
    }

    private void ShowPolicy(Int64 DocumentId)
    {
        ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
        ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

        _policydoc = _policydocdb.GetProviderPolicyDocument(DocumentId);

        if (_policydoc != null)
        {
            lblProviderCarPolicyId.Text = _policydoc.DocumentId.ToString();
            txtPolicyDoc.Text = _policydoc.DocumentName;
            txtPolicyDescription.Text = _policydoc.Description;
            lnkpolicydoc.NavigateUrl = _policydoc.UploadPath.ToString();
            lnkpolicydoc.Text = _policydoc.DocumentName;
            chkStatus.Checked = Convert.ToBoolean(_policydoc.Status);
        }

    }

    public void ClearProcess()
    {
        _providerdocumentid = 0;
        lblProviderCarPolicyId.Text = "0";
        txtPolicyDoc.Text = "";
        txtPolicyDescription.Text = "";
        lnkpolicydoc.Text = "";
        chkStatus.Checked = true;
        lblMessage.Text = "";

    }

    protected void btnClearForm_Click(object sender, EventArgs e)
    {
        ClearProcess();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
             string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
             if (CheckAuthCode(_authcode, 600))
             {
                 if (fleUpload.PostedFile != null)
                 {
                     HttpPostedFile myFile = fleUpload.PostedFile;
                     int fileSize = myFile.ContentLength;
                     FileInfo fInfo = new FileInfo(myFile.FileName);

                     if (fileSize > 0 && (fileSize / 1024) < 4096)
                     {
                         if (CheckExtension(fInfo.Extension) == true)
                         {

                             MyImage myImage = new MyImage();
                             // Allocate a buffer for reading of the file
                             byte[] myData = new byte[fileSize];

                             // Read uploaded file from the Stream
                             myFile.InputStream.Read(myData, 0, fileSize);

                             string providerFolder = "";
                             if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                                 providerFolder = "Liberty/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                                 providerFolder = "Etiqa/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                                 providerFolder = "HSBC/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChartisProviderCompanyId"))
                                 providerFolder = "Chartis/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
                                 providerFolder = "RSA/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChinaProviderCompanyId"))
                                 providerFolder = "ChinaTaiping/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EQProviderCompanyId"))
                                 providerFolder = "EQ/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ACEProviderCompanyId"))
                                 providerFolder = "ACE/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("1CoverProviderCompanyId"))
                                 providerFolder = "1Cover/";
                             else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("DAProviderCompanyId"))
                                 providerFolder = "DA/";



                             string strFilename = Path.GetFileName(myFile.FileName);
                             string _strDocPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UploadDocPath");
                             string uploadPath = Server.MapPath(_strDocPath + providerFolder + strFilename);

                             //check if directory exists
                             string directoryToUpload = uploadPath;


                             if (!Directory.Exists(directoryToUpload))
                             {
                                 //creates the folder
                                 string pathtocreate = Server.MapPath(_strDocPath + providerFolder.Remove(providerFolder.Length - 1, 1));
                                 Directory.CreateDirectory(pathtocreate);
                             }

                             if (!File.Exists(uploadPath))
                             {

                                 // Write data into a file
                                 myImage.WriteToFile(uploadPath, ref myData);

                                 ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
                                 ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

                                 _policydoc.DocumentId = Convert.ToInt64(lblProviderCarPolicyId.Text);
                                 int _trantype = 1;
                                 if (_policydoc.DocumentId > 0)
                                 {
                                     _trantype = 2;
                                 }
                                 _policydoc.DocumentName = txtPolicyDoc.Text.Trim();
                                 _policydoc.Description = txtPolicyDescription.Text.Trim();
                                 _policydoc.ForWhat = "TI";
                                 _policydoc.SizeKB = fileSize;
                                 _policydoc.UploadPath = _strDocPath + providerFolder + strFilename;
                                 _policydoc.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString());
                                 _policydoc.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                                 _policydoc.Status = Convert.ToBoolean(chkStatus.Checked.ToString());
                                 _policydoc.DocumentId = _policydocdb.Insert(_policydoc);

                                 if (_policydoc.DocumentId > 0)
                                 {
                                     InsertProviderAuthTransaction(_policydoc.DocumentId, "TIPolicy", _trantype, 600, _authcode, _policydoc.ProviderCompanyId, _policydoc.RefCEUserId);
                                     ClearProcess();
                                     lblMessage.Text = "Saved successfully!";
                                     Response.Redirect("ViewProviderTIPolicyWriting.aspx");
                                 }
                                 else
                                 {
                                     lblMessage.Text = "Saving failed!";
                                 }
                             }
                             else
                             {
                                 lblMessage.Text = "File already exists.";
                             }

                         }
                         else
                         {
                             lblMessage.Text = "Only PDF Files can be attached.";
                         }
                     }
                     else
                     {
                         lblMessage.Text = "File size should be under 4 MB.";
                     }
                 }

             }
             else
             {
                 lblMessage.Text = "Wrong auth code!";
             }

        }
    }

    protected void ibtBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewProviderTIPolicyWriting.aspx");
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        rfvAuthCode.Validate();
        if (lblProviderCarPolicyId.Text != "0" && txtAuthCode.Text.Trim().Length > 0)
        {
            Int64 _providercompanyid = Convert.ToInt64(Session[General.ProviderCompanyId].ToString());
            string _authcode = CE.Security.MySecurity.Encrypt(txtAuthCode.Text, true);
            Int64 _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
            if (CheckAuthCode(_authcode, 600))
            {
                ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();
                ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();

                _policydoc = _policydocdb.GetProviderPolicyDocument(Convert.ToInt64(lblProviderCarPolicyId.Text));
                FileInfo _file = new FileInfo(Server.MapPath(_policydoc.UploadPath));

                if (_policydocdb.Delete(Convert.ToInt64(lblProviderCarPolicyId.Text), _providercompanyid))
                {
                    if (_file.Exists)
                        _file.Delete();

                    InsertProviderAuthTransaction(Convert.ToInt64(lblProviderCarPolicyId.Text), "TICarPolicy", 3, 600, _authcode, _providercompanyid, _refceuserid);
                    Response.Redirect("ViewProviderTIPolicyWriting.aspx");
                }
                else
                {
                    lblMessage.Text = "Deleting failed.";
                }

            }
            else
            {
                lblMessage.Text = "Wrong auth code!";
            }
        }

    }


    private static bool CheckExtension(string Extension)
    {
        //string[] extList = { ".doc", ".pdf", ".docx", ".txt", ".rtf", ".ppt", ".pptx", ".xls" };
        string[] extList = { ".pdf" };
        bool isInList = false;
        for (int i = 0; i < extList.Length; i++)
        {
            if (Extension == extList[i])
            {
                isInList = true;
                break;
            }
        }
        return isInList;
    }

    protected bool CheckAuthCode(string strAuthCode, int intAuthCodeType)
    {
        bool _retValue = false;
        ProviderAuthCode _authcode = new ProviderAuthCode();
        ProviderAuthCodeDB _authcodedb = new ProviderAuthCodeDB();
        _authcode = _authcodedb.GetProviderAuthCode(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()), intAuthCodeType, strAuthCode);
        if (_authcode != null)
        {
            _retValue = true;
        }

        return _retValue;
    }

    protected Int64 InsertProviderAuthTransaction(Int64 TransactionId, string TransactionCode, int TransactionType,
        int AuthCodeType, string AuthCode, Int64 ProviderCompanyId, Int64 RefCEUserId)
    {
        ProviderAuthTransaction _authtrans = new ProviderAuthTransaction();
        ProviderAuthTransactionDB _authtransdb = new ProviderAuthTransactionDB();

        _authtrans.TransactionId = TransactionId;
        _authtrans.TransactionCode = TransactionCode;
        _authtrans.TransactionType = TransactionType;
        _authtrans.AuthCode = AuthCode;
        _authtrans.AuthCodeType = AuthCodeType;
        _authtrans.ProviderCompanyId = ProviderCompanyId;
        _authtrans.RefCEUserID = RefCEUserId;

        _authtrans.AuthTransId = _authtransdb.Insert(_authtrans);
        return _authtrans.AuthTransId;
    }

    private void CheckMainPageAccess()
    {
        Int64 PageAccess = General.GetProviderMainPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), PageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
    }

    private void CheckSubPageAccess()
    {
        Int64 PageAccess = General.GetProviderSubPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), SubPageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
        else if (PageAccess == 100)
        {
            ibtSubmit.Enabled = false;
            btnNew.Enabled = false;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            btnDelete.Enabled = true;
        }
    }

}
